package com.springcloud.gateway.handler;

import com.springcloud.gateway.provider.ResponseProvider;
import lombok.extern.slf4j.Slf4j;
import org.springframework.boot.autoconfigure.web.ErrorProperties;
import org.springframework.boot.autoconfigure.web.ResourceProperties;
import org.springframework.boot.autoconfigure.web.reactive.error.DefaultErrorWebExceptionHandler;
import org.springframework.boot.web.reactive.error.ErrorAttributes;
import org.springframework.cloud.gateway.support.NotFoundException;
import org.springframework.context.ApplicationContext;
import org.springframework.web.reactive.function.server.ServerRequest;
import org.springframework.web.server.ResponseStatusException;

import java.util.Map;

/**
 * @version V1.0
 * @Author 宋聚智
 * @Date 2019/11/1 15:55
 * @description
 * @Modify By：
 * @ModifyTime： 2019/11/1
 * @Modify marker：
 **/

//异常处理
@Slf4j
public class ErrorExceptionHandler extends DefaultErrorWebExceptionHandler {
    public ErrorExceptionHandler(ErrorAttributes errorAttributes, ResourceProperties resourceProperties, ErrorProperties errorProperties, ApplicationContext applicationContext) {
        super(errorAttributes, resourceProperties, errorProperties, applicationContext);
    }

    @Override
    public Map<String,Object> getErrorAttributes(ServerRequest request, boolean includeStackTrace){
        int code=500;
        Throwable error= super.getError(request);

        if(error instanceof NotFoundException){
            code =404;
        }
        if(error instanceof ResponseStatusException){
            code=((ResponseStatusException) error).getStatus().value();
        }
        return ResponseProvider.response(code,this.buildMessage(request,error));
    }


    //构建异常信息
    private String buildMessage(ServerRequest request,Throwable ex){
        StringBuilder message= new StringBuilder("Failed to handle request [");
        message.append(request.methodName());
        message.append(" ");
        message.append(request.uri());
        message.append("]");
        if(ex != null){
            message.append(": ");
            message.append(ex.getMessage());
        }
        return  message.toString();
    }
}
